package zhuyouyong;

/**
 * @author zhuyouyong <zhuyouyong@hangsheng.com.cn>
 * Created on 2021/3/18.
 */
public class ObfuscatePlugin /*implements Plugin<Project>*/ {
    /*private boolean injected;

    @Override
    public void apply(Project project) {
        // injectObfuscator(project);
        AppExtension app = project.getExtensions().getByType(AppExtension.class);
        app.registerTransform(new ObfuscateTransform(project), Collections.EMPTY_LIST);
    }

    private void injectObfuscator(Project project) {
        project.getTasks().whenTaskAdded(task -> {
            if (!injected && isCompileTask(task.getName())) {
                injected = true;
                task.doLast(compileTask -> {
                    String path = "";
                    String asPath = compileTask.getOutputs().getFiles().getAsPath();
                    String[] splits = asPath.split(";");
                    if (splits.length > 1) {
                        for (String split : splits) {
                            if (split.endsWith("classes")) {
                                path = split;
                                break;
                            }
                        }
                    } else path = splits[0];
                    executeInject(path);
                });
            }
        });
    }

    private boolean isCompileTask(String taskName) {
        return taskName.contains("compile") && (
                taskName.contains("Kotlin") || taskName.contains("JavaWithJavac")
        );
    }

    private void executeInject(String path) {
        new Thread(() -> {
            String obfuscator =
                    OooOO0OO.class.getName().replace(".", "/") + ".class";
            String injectPath = path + File.separator + obfuscator;
            File injectDir = new File(injectPath).getParentFile();
            if (!injectDir.exists()) injectDir.mkdirs();
            try(
                    InputStream input =
                            OooOO0OO.class.getClassLoader().getResourceAsStream(obfuscator);
                    FileOutputStream output = new FileOutputStream(injectPath)
            ) {
                byte[] bytes = new byte[input.available()];
                input.read(bytes);
                output.write(bytes);
                output.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }*/
}
